import React from 'react';
import { render } from 'react-dom';

import { Modal, Form, Input, Button, Icon, Upload, Tag, Tooltip } from 'antd';

import { WebTool } from '../lib/webtool';

const { TextArea } = Input;
class InnerForm extends React.Component {
    state = {
        swapItems:[],
        previewVisible: false,
        previewImage: '',
        fileList: [],
        inputVisible: false,
        inputValue: ''
    };

    setPhotoMsg = () => {
        let photo = "";
        try {
            photo = this.state.fileList[0].response.url;
        } catch (e) { }

        if (!photo) {
            this.setState({ uploadRequireMsg: "Please upload your item photo!" });
        } else {
            this.setState({ uploadRequireMsg: "" });
        }
    };

    setSwapMsg = () => {
        if (this.state.swapItems.length <= 0) {
            this.setState({ swapRequireMsg: "Please add the items that you want to swap!" });
            return false;
        } else {
            this.setState({ swapRequireMsg: "" });
            return true;
        }
    }

    handleSubmit = e => {
        e.preventDefault();

        let photo = "";
        try {
            photo = this.state.fileList[0].response.url;
        } catch (e) { }

        var res = this.setSwapMsg();
        if(!photo){
            this.setState({uploadRequireMsg:"Please upload your item photo!"});
            return;
        }else{
            this.setState({uploadRequireMsg:""});
        }

        if (!res) {
            return;
        }

        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.photo = photo;
                values.swapItems = this.state.swapItems;
                WebTool.post('/main/addItem', values, json => {
                    WebTool.success('Save item success');
                    if(this.props.onCancel){
                        this.props.onCancel(true);
                    }
                });
            }
        });
    };

    getBase64 = (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }

    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = file => {
        if (!file.url && !file.preview) {
            this.getBase64(file.originFileObj).then(data => {
                file.preview = data;
                this.setState({
                    previewImage: file.url || file.preview,
                    previewVisible: true,
                });
            });
        }
        else {
            this.setState({
                previewImage: file.url || file.preview,
                previewVisible: true,
            });
        }
    };

    handleChange = ({ fileList }) => {
        this.setState({ fileList });
        this.setPhotoMsg()
    };
    
    handleRemovedSwap = removedSwapItem => {
        const swapItems = this.state.swapItems.filter(tag => tag !== removedSwapItem);
        this.setState({ swapItems }, ()=>this.setSwapMsg());
    };
    showInput = () => {
        this.setState({ inputVisible: true }, () => this.input.focus());
    };
    handleInputChange = e => {
        this.setState({ inputValue: e.target.value });
    };
    handleInputConfirm = () => {
        const { inputValue } = this.state;
        let { swapItems } = this.state;
        if (inputValue && swapItems.indexOf(inputValue) === -1) {
            swapItems = [...swapItems, inputValue];
        }
        console.log(swapItems);
        this.setState({
            swapItems,
            inputVisible: false,
            inputValue: '',
        },()=>this.setSwapMsg());
        // this.setSwapMsg();
    };
    saveInputRef = input => (this.input = input);

    render() {
        const { getFieldDecorator } = this.props.form;
        const { previewVisible, previewImage, fileList } = this.state;

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };

        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload</div>
            </div>
        );

        return (
            <div>
                <Form {...formItemLayout} onSubmit={this.handleSubmit} id="myItemDetailForm">
                    <Form.Item label="Item name">
                        {getFieldDecorator('name', {
                            rules: [
                                {
                                    required: true,
                                    message: 'Please input your item name!',
                                    whitespace: true
                                },
                            ],
                        })(<Input />)}
                    </Form.Item>
                    <Form.Item label="Description">
                        {getFieldDecorator('description', {
                            rules: [{ required: true, message: 'Please input your item description!', whitespace: true }],
                        })(<TextArea rows={4} />)}
                    </Form.Item>
                    <Form.Item label="Photo">
                        <Upload
                            accept="image/*"
                            action="/file/upload"
                            listType="picture-card"
                            data={{ fileType: 'item_photo' }}
                            fileList={fileList}
                            onPreview={this.handlePreview}
                            onChange={this.handleChange}
                        >
                            {fileList.length >= 1 ? null : uploadButton}
                        </Upload>
                        <div style={{ color: "#f5222d", lineHeight: "16px" }}>{this.state.uploadRequireMsg}</div>
                    </Form.Item>

                    <Form.Item label="Swap items">
                        <div>
                            {this.state.swapItems.map((tag, index) => {
                                const isLongTag = tag.length > 20;
                                const tagElem = (
                                    <Tag key={tag} closable={true} onClose={() => this.handleRemovedSwap(tag)}>
                                        {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                                    </Tag>
                                );
                                return isLongTag ? (
                                    <Tooltip title={tag} key={tag}>
                                        {tagElem}
                                    </Tooltip>
                                ) : (
                                        tagElem
                                    );
                            })}
                            {this.state.inputVisible && (
                                <Input
                                    ref={this.saveInputRef}
                                    type="text"
                                    size="small"
                                    style={{ width: 78 }}
                                    value={this.state.inputValue}
                                    onChange={this.handleInputChange}
                                    onBlur={this.handleInputConfirm}
                                    onPressEnter={this.handleInputConfirm}
                                />
                            )}
                            {!this.state.inputVisible && (
                                <Tag onClick={this.showInput} style={{ background: '#fff', borderStyle: 'dashed' }}>
                                    <Icon type="plus" /> New Item
                            </Tag>
                            )}
                            <div style={{ color: "#f5222d", lineHeight: 0 }}>{this.state.swapRequireMsg}</div>
                        </div>
                    </Form.Item>
                    <Button type="primary" htmlType="submit" id="myItemDetailFormSumit" style={{display:"none"}}>Register</Button>
                </Form>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
}

const WrappedInnerForm = Form.create({ name: 'register' })(InnerForm);

export class MainMyItemsDetailComponent extends React.Component {
    constructor() {
        super();
    }
    state = {
        visible: false,
        confirmLoading: false,
        title: 'Add item'
    };

    handleOk = () => {
        // this.setState({
        //     confirmLoading: true,
        // });

        document.getElementById('myItemDetailFormSumit').click();
    };

    handleCancel = (reload) => {
        if (this.props.onClose) {
            this.props.onClose(reload === true);
        }
    };


    render() {
        const { confirmLoading } = this.state;

        return (
            <Modal
                centered
                title={this.props.title}
                visible={this.props.visible}
                onOk={this.handleOk}
                confirmLoading={confirmLoading}
                onCancel={this.handleCancel}
                width={800}
                okText="Save"
                maskClosable={false}
                destroyOnClose={true}
            >
                <WrappedInnerForm onCancel={this.handleCancel}></WrappedInnerForm>
            </Modal>
        );
    };
}